package org.example.service.impl;

import io.seata.rm.tcc.api.BusinessActionContext;
import org.example.dao.ResultDAO;
import org.example.pojo.Result;
import org.example.service.IResultTccAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class ResultTccAction implements IResultTccAction {
    private static final Logger logger = LoggerFactory.getLogger(ResultTccAction.class);

    @Autowired
    private ResultDAO resultDAO;

    @Override
    @Transactional
    public boolean prepare(BusinessActionContext businessActionContext, int id, int resultScore) {
        logger.info("result--try--开启");
        Result result = resultDAO.findOne(id);
        if(result == null){
            result = new Result();
            result.setId(id);
            result.setStudentid(1);
            result.setScore(resultScore);
            result.setStatus("0"); //冻结资源，置为无效
        }else{
            //此处可以进行隔离控制，进行写隔离。如果状态是无效状态则try阶段失败
            if("1".equals(result.getStatus())){
                logger.info("result--try--资源被占");
                return false;
            }
            result.setScore(resultScore);
            result.setStatus("0"); //冻结资源，置为无效
        }
        resultDAO.save(result);
        logger.info("result--try--提交");
        return true;
    }

    @Override
    @Transactional
    public boolean commit(BusinessActionContext businessActionContext) {
        logger.info("result--confirm--开启");
        int id = (int) businessActionContext.getActionContext("resultId");
        Result result = resultDAO.findOne(id);
        if(result == null){
            logger.info("result--confirm--失败");
            return false;
        }else{
            //操作自己冻结的资源
            result.setStatus("1");
            resultDAO.save(result);
        }
        logger.info("result--confirm--结束");
        return true;
    }

    @Override
    @Transactional
    public boolean rollback(BusinessActionContext businessActionContext) {
        logger.info("result--cancel--开启");
        int id = (int) businessActionContext.getActionContext("resultId");
        Result result = resultDAO.findOne(id);
        if(result != null){
            // 释放占用的资源
            result.setStatus("1");
        }
        logger.info("result--cancel--结束");
        return true;
    }
}
